<?php
namespace api\middleware;

use Darabonba\GatewaySpi\Models\InterceptorContext\request;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class CheckToken
{
    public function handle($request ,\Closure $next)
    {
        //验证token
        $header = $request->header();

        if(!isset($header['token']) || empty($header['token'])){
            return json([
                'code' => 0,
                'msg' => '缺少token',
            ]);
        }
        $key = new Key(config('app.jwt_key'),'HS256');
        try {
            $res = JWT::decode($header['token'],$key);
        }catch (\Exception $exception){
            return json([
                'code' => 0,
                'msg' => $exception->getMessage()
            ]);
        }
        $request->userId = $res->data->user_id;
        return $next($request);
    }

}